<?php
namespace app\adm\controller;
use think\Controller;
use think\Db;
use think\Request;

/**
 * rbac权限控制
 */
class Rule extends Index{
	public function __construct(Request $request){
		parent::__construct($request);
	}

	/*
	* 权限管理页
	*/
	public function rule(Request $request){
		$data = Db::name('auth_rule')->order('id asc')->select();

		$list = tree($data,'tree');unset($data);
		$this->assign('list',$list);
		return $this->fetch($request->action(),['title'=>'权限管理']);
	}
	
	
	/*
	* 修改权限信息
	*/
	public function update_rule(Request $request){
		if($request->isAJax()){
			$data = input('post.');

			$res = Db::name('auth_rule')->where(['id'=>$data['id']])->update(['title'=>$data['updateTitle'],'name'=>$data['ruleName']]);
			if($res){
                adminOperationRecord('修改了一条权限信息，标题为：'.$data['updateTitle'].' 内容为：'.$data['ruleName']);
				$this->success('修改成功！');
			}else{
				$this->error('修改失败！');
			}
		}
	}

	/*
	* 添加权限（包括子权限）
	*/
	public function add_rule(Request $request){
		if($request->isAJax()){
			$data = input('post.');

			$datas = [
				'title'	=> $data['title'],
				'name'	=> $data['name'],
				'pid'	=> $data['pid'],
			];
			$res = Db::name('auth_rule')->insert($datas);
			if($res){
                adminOperationRecord('添加了一条权限信息，标题为：'.$data['title'].'，内容为：'.$data['name']);
				$this->success('添加成功！');
			}else{
				$this->error('添加失败！');
			}
		}
	}

	/*
	* 删除权限（包括子权限）
	*/
	public function delete_rule(Request $request){
		if($request->isAJax()){
			$id = input('post.id');

			$count = Db::name('auth_rule')->where(['pid'=>$id])->count();

            if($count >= 1){
            	$this->error('尚有子菜单，不能删除！');
            }
            $title = Db::name('auth_rule')->where(['id'=>$id])->value('title');
            $res = Db::name('auth_rule')->where(['id'=>$id])->delete();
            if($res){
                adminOperationRecord('删除了一条权限信息，标题为：'.$title);
                $this->success();
            }else{
                $this->error('删除失败');
            }
		}
	}

	/*
	* 分配权限
	*/
	public function rule_group($group_id,Request $request){
            $group = Db::name('auth_group')->where(['id'=>$group_id])->find();
		if(!$request->isAJax()){
			$group['rules'] = explode(',', $group['rules']);
			$data = Db::name('auth_rule')->select();
			$list = tree($data,'level');unset($data);
			$this->assign('list',$list);
			$this->assign('group',$group);
			return $this->fetch($request->action(),['title'=>'权限管理']);
		}else{
			$formdata = input('post.formdata');

			$string = str_replace('&',',',str_replace('rule_ids=','',$formdata));

			$res = Db::name('auth_group')->where(['id'=>$group_id])->update(['rules'=>$string]);
			if($res){
                adminOperationRecord('进行了分配权限操作，标题为：'.$group['title']);
				$this->success('修改成功！');
			}else{
				$this->error('修改失败！');
			}
		}
	}

	/*
	* 用户组管理列表
	*/
    public function group(Request $request){
    	$list = Db::name('auth_group')->select();

		$this->assign('list',$list);
    	return $this->fetch($request->action(),['title'=>'用户组列表']);
    }

    /*
	* 删除用户组
    */
    public function group_delete($id,Request $request){
    	if($request->isAJax()){
            $count = Db::name('auth_user')->where(['group_id'=>$id])->count();

            if($id == 4){
                $this->error('讲师组不能删除！');
            }

            if($count >= 1){
            	$this->error('该管理组尚有用户，不能删除！');
            }
            $title = Db::name('auth_group')->where(['id'=>$id])->value('title');
            $res = Db::name('auth_group')->where(['id'=>$id])->delete();
            if($res){
                adminOperationRecord('删除了一个标题为：'.$title.' 的用户组');
                $this->success();
            }else{
                $this->error('删除失败');
            }
        }
    }

    /*
	* 添加用户组
    */
    public function group_insert(Request $request){
    	if($request->isAJax()){

            $res = Db::name('auth_group')->insert(['title'=> trim(input('post.title'))]);

            if($res){
                adminOperationRecord('添加了一个名称为：'.input('post.title').' 的用户组');
                $this->success('添加成功！');
            }else{
                $this->error('添加失败！');
            }
        }
    }

    /*
	* 修改用户组
    */
    public function group_update(Request $request){
    	if($request->isAJax()){
    		$data = input('post.');

            $res = Db::name('auth_group')->where(['id'=>$data['id']])->update(['title'=> trim($data['title'])]);

            if($res){
                adminOperationRecord('修改了用户组信息，修改后为：'.$input('post.title'));
                $this->success('修改成功！');
            }else{
                $this->error('修改失败！');
            }
        }
    }

    /*
	* 管理员列表
    */
    public function auth_user_list(Request $request,$where=[],$search='',$group=''){

    	if(null != input('search')){
            $where['u.loginName'] = ['like','%'.input('search').'%'];
            $search = input('search');
        }
        if(null != input('group')){
            $where['u.group_id'] = input('group');
            $group = input('group');
        }

    	$data = Db::name('auth_user')->alias('u')
    		->field('u.uid,loginName,phone,email,ag.title, u.group_id')
    		->join('auth_group ag','u.group_id = ag.id')
    		->where($where)->select();
    	$group_list = Db::name('auth_group')->select();

		$this->assign('list',$data);
		$this->assign('group',$group_list);
		$this->assign('where',['search'=>$search , 'group'=>$group]);
    	return $this->fetch($request->action(),['title'=>'管理员列表']);
    }


    /*
	* 添加管理员
    */
    public function add_user(Request $request){
    	if(!$request->isAJax()){
    		$group_list = Db::name('auth_group')->select();
    		$this->assign('group',$group_list);
    		return $this->fetch($request->action(),['title'=>'添加管理员']);
    	}else{

    		$data = input('post.');

    		$find = Db::name('auth_user')->where(['loginName'=>$data['username']])->find();

    		if($find){
    			$this->error('用户名存在！~');
    		}

    		$users = [
    			'loginName'		=> $data['username'],
    			'loginPassword'	=> md5(md5($data['password'])),
    			'group_id'		=> $data['group_id'],
    			'email'			=> $data['email'],
    			'phone'			=> $data['phone'],
    			'register_date'	=> date('Y-m-d H:i:s'),
    		];
    		$res = Db::name('auth_user')->insert($users);
    		if($res){
                adminOperationRecord('添加了一个管理账号，账号为：'.$data['username']);
    			$this->success('添加成功！');
    		}else{
    			$this->error('添加失败！');
    		}
    	}
    }

    /*
	* 修改管理员
    */
    public function edit_user($id,Request $request){
            $user = Db::name('auth_user')->field('uid,group_id,email,phone,loginName')->where(['uid'=>$id])->find();
    	if(!$request->isAJax()){
    		$group_list = Db::name('auth_group')->select();
    		$this->assign('user',$user);
    		$this->assign('group',$group_list);
    		return $this->fetch($request->action(),['title'=>'修改管理员']);
    	}else{
    		$data = input('post.');
    		$res = Db::name('auth_user')->where(['uid'=>$data['id']])->update(['group_id'=>$data['group_id']]);
    		if($res){
                adminOperationRecord('进行了修改管理员权限操作，账号为：'.$user['loginName']);
    			$this->success('修改成功！');
    		}else{
    			$this->error('修改失败！');
    		}
    	}
    }
    /*
    * 删除管理员
    */
    public function del_user(Request $request){
        $where['uid'] = input('uid');
        $store=Db::name('store')->where($where)->find();
        if($store){
            jsBack('当前用户有门店,请先删除门店');
        }else{
            if($where=='1'){
                jsBack('当前为超级管理员,不可删除');
            }else{
                $user = Db::name('auth_user')->field('uid,group_id,loginName')->where($where)->find();
                $res = Db::name('auth_user')->where($where)->delete();
                if($res){
                    adminOperationRecord('进行了修改管理员权限操作，账号为：'.$user['loginName']);
                    jsBack('删除成功！');
                }else{
                    jsBack('删除失败！');
                }                
            }
        }
    }

	/*
    * 操作日志
    */
	public function log($id,Request $request){
		$data = Db::name('sys_log')
				->alias('l')->field('u.uid,loginName,l.*')
				->join('auth_user u','u.uid = l.uid')
				->where(['l.uid'=>$id])->order('l.id desc')->select();
		$this->assign('list',$data);
		return $this->fetch($request->action(),['title'=>'操作日志']);
	}
}
